<template>
  <el-row v-if="show">
    <el-col :span="7">
      <div class="commManage-left">
        <el-scrollbar @scroll="showMenu ? (showMenu = false) : undefined">
          <ul>
            <li>
              <router-link
                class="commManage-left__all"
                :to="{ name: 'commManageFriends', params: { title: 'all' } }"
                exact-active-class="active-listLi--item"
              >
                <span class="item-tag">全部</span>
                <span class="item-count">({{ friendsLen }})</span>
              </router-link>
            </li>
            <li>
              <div
                class="commManage-left__title"
                @click="handleToActiveName('permission')"
              >
                <span class="item-tag">朋友权限</span>
                <SvgIcon
                  icon-class="rightArrow"
                  :class="{
                    'arrow-icon': true,
                    'arrow-icon__collapse': activeName === 'permission',
                  }"
                />
              </div>
              <el-collapse-transition>
                <ul v-show="activeName === 'permission'">
                  <li>
                    <router-link
                      class="commManage-left__item"
                      :to="{
                        name: 'commManageFriends',
                        params: { title: 'disabledOtherLook' },
                      }"
                      exact-active-class="active-listLi--item"
                    >
                      <span class="momentsPermission-icons">
                        <SvgIcon popper-class="moments-icon" icon-class="moments" />
                        <SvgIcon
                          popper-class="moments-icon__locked"
                          icon-class="lockClose"
                        />
                      </span>
                      <span class="item-tag">不让对方看</span>
                      <span class="item-count"
                        >({{
                          friendsManage.get("disabledOtherLook")?.noGroups?.count
                        }})</span
                      >
                    </router-link>
                  </li>
                  <li>
                    <router-link
                      class="commManage-left__item"
                      :to="{
                        name: 'commManageFriends',
                        params: { title: 'disabledSelfLook' },
                      }"
                      exact-active-class="active-listLi--item"
                    >
                      <span class="momentsPermission-icons">
                        <SvgIcon popper-class="moments-icon" icon-class="moments" />
                        <SvgIcon
                          popper-class="moments-icon__locked"
                          icon-class="eyeOff"
                        />
                      </span>
                      <span class="item-tag">不看对方</span>
                      <span class="item-count"
                        >({{
                          friendsManage.get("disabledSelfLook")?.noGroups?.count
                        }})</span
                      >
                    </router-link>
                  </li>
                </ul></el-collapse-transition
              >
            </li>
            <li>
              <div class="commManage-left__title" @click="handleToActiveName('group')">
                <span class="item-tag">分组</span>
                <SvgIcon
                  icon-class="rightArrow"
                  :class="{
                    'arrow-icon': true,
                    'arrow-icon__collapse': activeName === 'groups',
                  }"
                />
              </div>
              <el-collapse-transition>
                <ul v-show="activeName === 'groups'">
                  <li
                    v-for="[group, { count }] in friendsManage.get('groups')?.groups"
                    :key="group"
                  >
                    <router-link
                      :class="{
                        'commManage-left__item': true,
                        'active-listLi--item': activeGroup === group,
                      }"
                      :to="{
                        name: 'commManageFriends',
                        params: { title: 'groups' },
                        query: { type: group },
                      }"
                      @contextmenu="openMenu(group, $event)"
                    >
                      <span class="item-tag" :title="group">{{ group }}</span>
                      <span class="item-count">({{ count }})</span>
                    </router-link>
                  </li>
                  <li class="commManage-setGroup" @click="openDialog">
                    <SvgIcon icon-class="create" />
                    创建分组
                  </li>
                </ul></el-collapse-transition
              >
            </li>
          </ul></el-scrollbar
        >
        <confirm-dialog
          to=".chat-box"
          v-model="showDialog"
          width="35%"
          title="创建分组"
          :isLoading="isLoading"
          @confirm="confirm"
        >
          <el-input
            v-model.trim="newGroup"
            ref="groupRef"
            :disabled="isLoading"
            maxlength="16"
            placeholder="输入新的分组名"
            @keypress.enter.prevent="confirm"
            style="width: 70%"
        /></confirm-dialog>
        <rig-click-menu
          ref="menu"
          v-model="showMenu"
          :group="rigClickGroup"
        ></rig-click-menu>
      </div>
    </el-col>
    <el-col :span="17" id="commManageRight" class="commManage-right"
      ><div style="height: 100%">
        <div class="chat-logo flex" v-show="route.name === 'commManage'">
          <SvgIcon icon-class="logo" />
        </div>
        <router-view /></div
    ></el-col> </el-row
  ><template v-else
    ><feed-back
      :is-requesting="isRequesting"
      :is-error="isError"
      message="请求出错啦"
      @retry="getFriendsManage"
    ></feed-back
  ></template>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, onBeforeUnmount, nextTick, watch } from "vue";
import { useFriendPinia } from "@/pinia/friend";
import { useUserPinia } from "@/pinia/user";
import { storeToRefs } from "pinia";
import { useRoute, useRouter } from "vue-router";
import feedBack from "@/components/ui-components/feedBack.vue";
import SvgIcon from "@/components/svgIcon/index.vue";
import confirmDialog from "@/components/confirmDialog.vue";
import { ElMessage } from "element-plus";
import rigClickMenu from "./rigClickMenu.vue";
import Trigger from "@/plugins/rigClickOpMen";

const friendStore = useFriendPinia();
const { friendsLen, friendsManage, isRequFriendsManage } = storeToRefs(friendStore);
const { user } = storeToRefs(useUserPinia());

const route = useRoute();
const router = useRouter();

/**
 * 当前用户是选择朋友权限还是分组
 */
const activeName = ref<"permission" | "groups" | "">("");
/**
 * 当前用户查看的分组名
 */
const activeGroup = ref<string>("");

watch(
  () => route.query.type as string,
  (newType) => (activeGroup.value = newType)
);

const handleToActiveName = (name: "permission" | "group") => {
  if (name === "permission") {
    if (activeName.value === "permission") activeName.value = "";
    else activeName.value = "permission";
  } else if (activeName.value === "groups") activeName.value = "";
  else activeName.value = "groups";
};

/**
 * 是否显示好友的详情信息
 */
const show = ref<boolean>(false);
/**
 * 是否正在请求好友的详情消息
 */
const isRequesting = ref<boolean>(false);
/**
 * 请求是否出错
 */
const isError = ref<boolean>(false);

// 请求通讯管理数据
const getFriendsManage = () => {
  return new Promise<number>((resolve) => {
    if (isError.value) isError.value = false;
    if (show.value) show.value = false;
    isRequesting.value = true;
    friendStore
      .getFriendsManage()
      .then((code: number) => {
        isRequesting.value = false;
        if (code === 1) show.value = true;
        else isError.value = true;
        resolve(code);
      })
      .catch(() => {
        isRequesting.value = false;
        isError.value = true;
      });
  });
};

const trigger = ref<Trigger>();
onBeforeMount(() => {
  if (!isRequFriendsManage.value)
    getFriendsManage().then((code: number) => {
      if (code === 1) {
        const title: string = route.params.title as string;
        if (title === "disabledOtherLook" || title === "disabledSelfLook")
          activeName.value = "permission";
        else if (title === "groups") {
          const type: string = route.query.type as string;
          if (!friendsManage.value.get("groups")?.groups?.has(type))
            router.replace({ name: "commManage" });
          else {
            activeName.value = "groups";
            activeGroup.value = type;
          }
        }
        const ele: HTMLElement = document.querySelector(
          ".commManage-left"
        ) as HTMLElement;
        trigger.value = new Trigger(ele);
        trigger.value.resize();
      }
    });
  else {
    show.value = true;
    nextTick(() => {
      const ele: HTMLElement = document.querySelector(".commManage-left") as HTMLElement;
      trigger.value = new Trigger(ele);
      trigger.value.resize();
    });
  }
});

/**
 * 是否显示操作确认对话框
 */
const showDialog = ref<boolean>(false);
/**
 * 是否正在执行某项操作
 */
const isLoading = ref<boolean>(false);
/**
 * 给设置分组输入框一个ref属性
 */
const groupRef = ref<any>();
/**
 * 新的分组名
 */
const newGroup = ref<string>("");
/**
 * 打开创建分组对话框
 */
const openDialog = () => {
  showDialog.value = true;
  setTimeout(() => groupRef.value.focus(), 200);
};
// 确定创建
const confirm = () => {
  if (!newGroup.value) showDialog.value = false;
  else if (!isLoading.value)
    if (!friendStore.friendsManage.get("groups")?.groups?.has(newGroup.value)) {
      isLoading.value = true;
      friendStore
        .createGroup({
          selfId: user.value.userId,
          group: newGroup.value,
        })
        .then((code: number) => {
          isLoading.value = false;
          newGroup.value = "";
          if (code === 1) {
            showDialog.value = false;
            ElMessage({
              type: "success",
              message: "创建成功",
              duration: 1500,
            });
          } else {
            ElMessage({
              type: "error",
              message: "创建失败",
              duration: 1500,
            });
            groupRef.value.focus();
          }
        })
        .catch(() => {
          isLoading.value = false;
          newGroup.value = "";
          ElMessage({
            type: "error",
            message: "创建失败",
            duration: 1500,
          });
          groupRef.value.focus();
        });
    } else
      ElMessage({
        type: "error",
        message: "该分组已存在",
        duration: 1500,
      });
};

/**
 * 是否需要打开鼠标右击后出现的菜单
 */
const showMenu = ref<boolean>(false);
/**
 * 给鼠标右击出现的菜单元素组件一个ref属性，便于通过$refs访问
 */
const menu = ref<typeof rigClickMenu>();
/**
 * 当前用户鼠标右击的分组名
 */
const rigClickGroup = ref<string>("");

/**
 * 鼠标右键打开操作菜单
 */
const openMenu = (itemGroup: string, $event: MouseEvent): void => {
  if (itemGroup !== "无分组") {
    $event.preventDefault();
    showMenu.value = true;
    rigClickGroup.value = itemGroup;
    nextTick(() =>
      trigger.value?.computedDirection(menu.value?.$refs.menu as HTMLDListElement, $event)
    );
  }
};

onBeforeUnmount(() => trigger.value?.removeResize());
</script>

<style lang="scss" scoped>
.chat-logo {
  height: 100%;
  font-size: 70px;
  color: $logoColor;
}

.commManage {
  &-left {
    %thame {
      display: flex;
      align-items: center;
      padding: 15px 6%;
      transition: background-color 0.25s;
      cursor: pointer;
      font-size: 14px;
      box-sizing: border-box;
    }

    height: 500px;
    border-right: 1px solid rgb(220, 220, 224);
    background-color: $bkColorSty;

    &__title {
      @extend %thame;

      .arrow-icon {
        color: #b1b3b8;
        font-size: 12px;
        margin-left: auto;
        transition: transform 0.3s;

        &__collapse {
          transform: rotate(90deg);
        }
      }
    }

    &__all {
      @extend %thame;

      &:hover {
        background-color: rgba(193, 191, 191, 0.114);
      }
    }

    &__item {
      @extend %thame;
      padding-left: 13% !important;

      &:hover {
        background-color: rgba(193, 191, 191, 0.114);
      }
    }

    .item {
      &-tag {
        display: inline-block;
        max-width: 67%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #333;
      }

      &-count {
        color: #73767a;
        margin-left: 2%;
      }
    }

    .momentsPermission-icons {
      position: relative;
      margin-right: 5%;
      color: rgba(0, 0, 0, 0.432);

      .moments-icon {
        font-size: 22px;
        opacity: 0.6;

        &__locked {
          font-size: 15px;
          position: absolute;
          opacity: 0.9;
          right: 0;
          bottom: 0;
        }
      }
    }
  }

  &-right {
    position: relative;
  }

  &-setGroup {
    cursor: pointer;
    font-size: 14px;
    padding: 15px 13%;
    color: #333;

    &:hover {
      color: #000;
    }
  }
}
</style>
